﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;

namespace Api1.Helper
{
    class ByteHelper
    {
        public static string GetBase64(string filepath)
        {
            FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);

            byte[] byteFile = new byte[fs.Length];

            fs.Read(byteFile, 0, Convert.ToInt32(fs.Length));

            fs.Close();

           return Convert.ToBase64String(byteFile);

        }

        /// <summary>
        /// long转byte数组
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public static byte[] ConvertIntToByteArray(long m)
        {
            byte[] arry = new byte[6];
            arry[0] = (byte)(m & 0xFF);
            arry[1] = (byte)((m & 0xFF00) >> 8);
            arry[2] = (byte)((m & 0xFF0000) >> 16);
            arry[3] = (byte)((m >> 24) & 0xFF);
            arry[4] = (byte)((m >> 32) & 0xFF);
            arry[5] = (byte)((m >> 40) & 0xFF);
            return arry;
        }
        /// <summary>
        /// byte数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ToHexString(byte[] bytes) // 0xae00cf => "AE00CF "
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();

                for (int i = 0; i < bytes.Length; i++)
                {
                    strB.Append(bytes[i].ToString("X2"));
                }
                hexString = strB.ToString();
            }
            return hexString;
        }

        /// <summary>
        /// 16进制字符串转byte数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] strHexToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }



        /// <summary>
        /// 10进制字符串转16进制字符串
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string DexStrToHexStr(string s) {
            byte[] bData = BitConverter.GetBytes(long.Parse(s));
            string a = BitConverter.ToString(bData).Replace("-", "").Substring(0, 8);
            return a;
        }
    }
}
